<?php

namespace Yjius\EasyappYii\modules\ucenter\controllers;

use Yii;
use yii\helpers\HtmlPurifier;
use yii\rest\Controller;
use Yjius\common\Debug;
use Yjius\EasyappYii\modules\ucenter\services\AuthService;
use Yjius\EasyappYii\modules\ucenter\services\ResponseService;

class UcenterController extends Controller
{
    private $loginUser = [];

    protected $noNeedLoginRoute = [];

    public function init()
    {
        parent::init();

        if (!in_array(Yii::$app->requestedRoute, $this->noNeedLoginRoute)) {
            if (!$this->checkLogin()) {
                $this->error("登录失效", [], 401);
            }
        }
    }

    private function checkLogin()
    {
        //对token进行验证
        $token = \Yii::$app->request->headers->get("Authorization");
        //从get参数获取
        $token = $token ? $token : \Yii::$app->request->get("token");
        try {
            $this->loginUser = AuthService::checkLogin($token);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    //方便获取参数
    public function loadParam($pname, $default_value = null)
    {
        $request = Yii::$app->request;
        $pvalue = $request->isGet ? $request->get($pname, $default_value) : $request->post($pname, $default_value);
        $pvalue = is_array($pvalue) ? $pvalue : trim(HtmlPurifier::process($pvalue));
        return $pvalue;
    }

    //错误返回
    public function error($msg = "fail", $data = [], $code = 500)
    {
        if (isset(Yii::$app->easyappYiiUcenter)) {
            $this->endJson(Yii::$app->easyappYiiUcenter->error($msg, $data, $code));
        } else {
            $this->endJson(ResponseService::getInstance()->error($msg, $data, $code));
        }
    }

    //成功返回
    public function success($data = [], $msg = "success", $code = 200)
    {
        if (isset(Yii::$app->easyappYiiUcenter)) {
            $this->endJson(Yii::$app->easyappYiiUcenter->success($data, $msg, $code));
        } else {
            $this->endJson(ResponseService::getInstance()->success($data, $msg, $code));
        }
    }

    private function endJson($data = [])
    {
        $this->asJson($data);
        Yii::$app->end();
    }

    /**
     * @return array
     */
    public function getLoginUser(): array
    {
        return $this->loginUser;
    }

}